package cn.cht.controller;

import cn.cht.client.SentinelHandlersClass;
import cn.cht.pojo.AuthCode;
import cn.cht.service.AuthCodeService;
import cn.cht.service.EmailService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/api/code")
public class CodeController {

    public static final Logger log = LoggerFactory.getLogger(CodeController.class);

    @Autowired
    private AuthCodeService authCodeService;
    @Reference(timeout = 10000)
    private EmailService emailService;

    @GetMapping("create/{email}")
    @SentinelResource(value = "createEmail", fallback = "handleException")
    public boolean createEmail(@PathVariable String email)   {
        AuthCode code = authCodeService.create(email);
        log.info("email: {}, code: {}", email, code);
        boolean send = emailService.send(email, code.getCode());
        return send;
    }

    @GetMapping("validate/{email}/{code}")
    public Integer validate(@PathVariable String email, @PathVariable String code) {
        return authCodeService.validate(email, code);
    }


    // 整体要求和当时Hystrix一样，这里还需要在形参中添加BlockException参数，用于接收异常
    // 注意：方法是静态的
    public static Boolean handleException(String email, Throwable throwable) {
        // 当邮件微服务不可用或超时时,服务降价默认返回false,发送邮件失败
        System.out.println("执行降级方法!!!!!!!!");
        return true;
    }

}
